package com.sgzn.sgpay.service.impl;

import com.sgzn.sgpay.enums.ReturnResultState;
import com.sgzn.sgpay.enums.SeqFlagEnum;
import com.sgzn.sgpay.enums.SgsResponseCode;
import com.sgzn.sgpay.model.request.*;
import com.sgzn.sgpay.model.response.CurrentPageInfo;
import com.sgzn.sgpay.model.response.SgsResultResponse;
import com.sgzn.sgpay.model.response.result.PresentQueryPageResult;
import com.sgzn.sgpay.model.response.vo.DeviceInfoVo;
import com.sgzn.sgpay.model.response.vo.MerchantDevicePresentVo;
import com.sgzn.sgpay.persistence.dao.TPresentMapper;
import com.sgzn.sgpay.persistence.domain.TPresent;
import com.sgzn.sgpay.persistence.domain.TPresentExample;
import com.sgzn.sgpay.persistence.manager.DeviceDaoManager;
import com.sgzn.sgpay.service.SgsDeviceService;
import com.sgzn.sgpay.service.SgsPresentService;
import com.sgzn.sgpay.service.converter.AssembleSgsCommonHandle;
import com.sgzn.sgpay.service.support.SgsResponseUtil;
import com.sgzn.sgpay.util.ArgsUtils;
import com.sgzn.sgpay.util.PageCalculator;
import com.sgzn.sgpay.util.SeqUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by xxjs-gd-llf
 * DATETIME:2018/5/19 14:35
 * Description:礼品接口实现类
 */
@Service
@Slf4j
public class SgsPresentServiceImpl implements SgsPresentService {

    @Autowired
    private TPresentMapper tPresentMapper;

    @Resource
    private SgsDeviceService sgsDeviceService;

    @Resource
    private DeviceDaoManager deviceDaoManager;

    @Autowired
    private AssembleSgsCommonHandle assembleSgsCommonHandle;

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SgsResultResponse<String> addPresent(SgsPresentAddRequest request) {
        TPresent tPresent = new TPresent();
        tPresent.setPresentId(SeqUtil.getShortSeq(SeqFlagEnum.PRESENT_ID.getCode()));
        tPresent.setPresentName(request.getPresentName());
        tPresent.setMerchantId(request.getMchId());
        tPresent.setPresentPrice(Integer.valueOf(request.getPresentPrice()));
        tPresent.setCreatedBy(request.getMchId());
        tPresent.setCreatedAt(new Date());
        tPresent.setUpdatedAt(new Date());
        int num = 0 ;
        try{
            num =  tPresentMapper.insertSelective(tPresent);
        }catch (DataAccessException e) {
            log.error("插入响应流水日志异常.{}", e);
        }
        if (num == 1) {
            return SgsResponseUtil.INSTANCE.success(ReturnResultState.SUCCESS.getCode());
        } else {
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc(), ReturnResultState.FAIL.getCode());
        }
    }

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SgsResultResponse<String> deletePresent(SgsPresentDeleteRequest request) {
        TPresentExample  example = new TPresentExample();
        TPresentExample.Criteria criteria = example.createCriteria();
        criteria.andPresentIdEqualTo(request.getPresentId());
        int num = 0 ;
        try{
            num =  tPresentMapper.deleteByExample(example);
        }catch (DataAccessException e) {
            log.error("插入响应流水日志异常.{}", e);
        }
        if (num == 1) {
            return SgsResponseUtil.INSTANCE.success(ReturnResultState.SUCCESS.getCode());
        } else {
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc(), ReturnResultState.FAIL.getCode());
        }
    }

    @Override
    public SgsResultResponse<TPresent> queryPresent(SgsPresentQueryRequest request) {
        SgsResultResponse sgsResponse = new SgsResultResponse();
        TPresentExample tPresentExample = new TPresentExample();
        tPresentExample.createCriteria().andPresentIdEqualTo(request.getPresentId());
        List<TPresent> tPresents = tPresentMapper.selectByExample(tPresentExample);
        ArgsUtils.notEmpty(tPresents, SgsResponseCode.C_SHOP_NOT_FOUND.getResponseCode(), SgsResponseCode.C_SHOP_NOT_FOUND.getResponseDesc());
        sgsResponse = SgsResponseUtil.INSTANCE.success(tPresents.get(0));
        return  sgsResponse;
    }

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SgsResultResponse<String> updatePresent(SgsPresentUpdateRequest request) {
        TPresent record = new TPresent();
        record.setPresentId(request.getPresentId());
        record.setPresentName(request.getPresentName());
        record.setPresentPrice(Integer.valueOf(request.getPresentPrice()));
        record.setUpdatedBy(request.getMchId());
        record.setUpdatedAt(new Date());

        TPresentExample example = new TPresentExample();
        TPresentExample.Criteria criteria = example.createCriteria();
        criteria.andPresentIdEqualTo(request.getPresentId());
        int num = 0 ;
        try{
            num =  tPresentMapper.updateByExampleSelective(record, example);
        }catch (DataAccessException e) {
            log.error("插入响应流水日志异常.{}", e);
        }
        if (num == 1) {
            return SgsResponseUtil.INSTANCE.success(ReturnResultState.SUCCESS.getCode());
        } else {
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc(), ReturnResultState.FAIL.getCode());
        }
    }

    @Override
    public SgsResultResponse<PresentQueryPageResult> queryPage(SgsPresentQueryPageRequest request) {
        //分页查询
        PresentQueryPageResult result = new PresentQueryPageResult();
        TPresentExample example = this.getTPresentExampleByPage(request);
        int totalCount = this.tPresentMapper.countByExample(example);//获取总数
        CurrentPageInfo pageInfo = PageCalculator.getPageInfo(totalCount, request.getPageQueryParam().getPageSize(),
                request.getPageQueryParam().getCurrentPage());
        StringBuffer clause = new StringBuffer();
        //加上起始和结束行号进行列表查询
        clause.append("present_id,updated_at desc ");
        clause.append("limit ").append(pageInfo.getStartIndex()).
                append(",").append(pageInfo.getPageSize());
        example.setOrderByClause(clause.toString());
        List<TPresent> list = tPresentMapper.selectByExample(example);

        result.setPresentList(list);
        result.setCurrentPage(pageInfo.getCurrentPage());
        result.setPageSize(pageInfo.getPageSize());
        result.setTotalCount(totalCount);
        result.setTotalPage(pageInfo.getTotalPage());
        return SgsResponseUtil.INSTANCE.success(result);
    }

    @Override
    /**
     * 返回设备礼品列表
     */
    public SgsResultResponse<List<TPresent>> queryList(SgsDevicePresentVoQuerytRequest request) {
        TPresentExample example = new TPresentExample();
        TPresentExample.Criteria cra = example.createCriteria();
        cra.andMerchantIdEqualTo(request.getMchId());
        List<TPresent> list = tPresentMapper.selectByExample(example);
        return SgsResponseUtil.INSTANCE.success(list);
    }


    /**
     * 返回设备礼品列表及库存数量
     */
    @Override
    public  SgsResultResponse<MerchantDevicePresentVo> queryDevicePresentVo (SgsDevicePresentVoQuerytRequest request){

        SgsResultResponse<MerchantDevicePresentVo> voSgsResultResponse = new SgsResultResponse<>();
        MerchantDevicePresentVo merchantDevicePresentVo = new MerchantDevicePresentVo();

        //查询礼品列表
        SgsResultResponse<List<TPresent>>  listSgsResultResponse = this.queryList(request );

        //查询设备信息
        SgsDeviceMchQueryRequest sgsDeviceQueryRequest = new SgsDeviceMchQueryRequest();
        sgsDeviceQueryRequest.setDeviceId( request.getDeviceId() );
        assembleSgsCommonHandle.assemble(request,sgsDeviceQueryRequest);
        sgsDeviceQueryRequest.setMchId(request.getMchId());
        SgsResultResponse<DeviceInfoVo>  deviceInfoVoSgsResultResponse = sgsDeviceService.queryMchDeviceInfo( sgsDeviceQueryRequest );

        if (deviceInfoVoSgsResultResponse == null ){
            log.info("没有找到对应的DeviceId{} ",request.getDeviceId());
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc());
        }
        voSgsResultResponse.setErrorMsg(deviceInfoVoSgsResultResponse.getErrorMsg());
        voSgsResultResponse.setErrorCode(deviceInfoVoSgsResultResponse.getErrorCode());
        merchantDevicePresentVo.setSelectedPresentId(deviceInfoVoSgsResultResponse.getResult().getPresentId() );
        merchantDevicePresentVo.setSelectedPresentStock(deviceInfoVoSgsResultResponse.getResult().getPresentStock()  );
        merchantDevicePresentVo.setTPresentList(listSgsResultResponse.getResult());
        voSgsResultResponse.setResult(merchantDevicePresentVo );
        return  voSgsResultResponse;
    }

    /**
     * 获取查询对象
     * @param request
     * @return
     */
    private TPresentExample  getTPresentExampleByPage(SgsPresentQueryPageRequest request){
        TPresentExample countExample = new TPresentExample();
        TPresentExample.Criteria cra = countExample.createCriteria();
        if(StringUtils.isNotBlank(request.getMchId())){
            cra.andMerchantIdEqualTo(request.getMchId());
        }
        return countExample;
    }
}
